from django.contrib import admin
from models import Professeur, Horaire, ActiviteUf, Ventilation, PlageHoraire

class VentilationInline(admin.TabularInline):
    model = Ventilation
    extra = 0

class PlageHoraireInline(admin.TabularInline):
    readonly_fields = ['periodes']
    model = PlageHoraire
    extra = 0

class HoraireAdmin(admin.ModelAdmin):
    readonly_fields = ['comptage_ventilation',]
    fields = ['uf', 'organisation', 'intitule', 'annee_scolaire', 'comptage_ventilation']
    inlines = [VentilationInline, PlageHoraireInline]
    list_display = ['intitule', 'annee_scolaire', 'uf']
    list_filter = ['annee_scolaire']

    def change_view(self, request, object_id, extra_context=None):
        def formfield_for_foreignkey_ventilation(self, db_field, request, **kwargs):
            if db_field.name == 'activite':
                try:
                    kwargs['queryset'] = ActiviteUf.objects.filter(uf__id=Horaire.objects.get(pk=object_id).uf.id).exclude(categorie__istartswith="Auto")
                except Exception:
                    pass
            return super(VentilationInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
        
        def formfield_for_foreignkey_plage_horaire(self, db_field, request, **kwargs):
            if db_field.name == 'activite_enseignement':
                try:
                    kwargs['queryset'] = Ventilation.objects.filter(horaire__id=Horaire.objects.get(pk=object_id).id)
                except Exception:
                    pass
            return super(PlageHoraireInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

        VentilationInline.formfield_for_foreignkey = formfield_for_foreignkey_ventilation
        PlageHoraireInline.formfield_for_foreignkey = formfield_for_foreignkey_plage_horaire

        self.inline_instances = [VentilationInline(self.model, self.admin_site), PlageHoraireInline(self.model, self.admin_site)]

        return super(HoraireAdmin, self).change_view(request, object_id, extra_context=extra_context)

    class Media:
        css = { "all" : ("css/hide_admin_original.css",) }


admin.site.register(Professeur)
admin.site.register(Horaire, HoraireAdmin)